package cn.yunbamboos.rest.service.apidoc.meta.schema;

import cn.yunbamboos.rest.service.apidoc.meta.Schema;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ObjectSchema extends BaseSchema {

    private final Map<String, Schema> properties = new HashMap<>();

    private final List<String> required = new ArrayList<>();

    public ObjectSchema(String path) {
        super(path,"object");
    }

    @Override
    public void addProperty(String name, Schema schema) {
        this.properties.put(name, schema);
    }

    @Override
    public void addRequired(String required) {
        this.required.add(required);
    }

    @Override
    public void toExample(JSONObject example) {
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Schema> entry : this.properties.entrySet()) {
            entry.getValue().toExample(json);
        }
        example.put(path, json);
    }

    @Override
    public JSONObject toJSON() {
        JSONObject json = super.toJSON();
        JSONObject properties = new JSONObject();
        for (Map.Entry<String, Schema> entry : this.properties.entrySet()) {
            properties.put(entry.getKey(), entry.getValue().toJSON());
        }
        json.put("properties", properties);
        json.put("required", required);
        return json;
    }
}
